package com.gin.kotlin.no_gay_alliance.database.dao

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.gin.kotlin.no_gay_alliance.database.entity.TopicHistory

@Dao
interface TopicHistoryDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun add(topicHistory: TopicHistory)

    /**
     * 按主题id查询
     *
     * @param topicId 主题id
     * @return 浏览历史
     */
    @Query("select * from TopicHistory where topicId=:topicId")
    fun get(topicId: Long): TopicHistory?

    /**
     * 分页查询
     *
     * @param keyword 关键字，检查范围： 楼主用户名，主题标题
     * @param page    页数
     * @param size    每页条数
     * @return 浏览历史
     */
    @Query("SELECT * FROM TopicHistory where 1=1 and (:keyword is null or authorName like '%' || :keyword || '%' or title like '%' || :keyword || '%') order by timestamp desc limit :size offset (:page-1)*:size ")
    fun page(page: Int, size: Int, keyword: String?=null): List<TopicHistory>?

    /**
     * 修改一个主题的"上次浏览的页数"
     *
     * @param topicId 主题id
     * @param page    页数
     */
    @Query("UPDATE TopicHistory SET page=:page where topicId=:topicId")
    fun updatePage(topicId: Long, page: Int)
}